﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Avivo.Tools.Sprite
{
	public partial class SpriteRow : List<SpriteItem>
	{
		#region Public properties
		/// <summary>
		/// Gets the total width - sum of all widths.
		/// </summary>
		public int Width
		{
			get
			{
				return this.Sum(x => x.Width);
			}
		}

		/// <summary>
		/// Gets the max height - a height of the heightest item.
		/// </summary>
		public int Height
		{
			get
			{
				int height = 0;
				foreach (var item in this)
				{
					height = Math.Max(height, item.Height);
				}
				return height;
			}
		}
		#endregion

		#region Serialization
		internal static SpriteRow Create(XElement element)
		{
			SpriteRow result = null;
			if (element.Name == "SpriteRow")
			{
				result = new SpriteRow();

				//int width = 0;
				//int.TryParse(element.Attribute("Width") != null ? element.Attribute("Width").Value : null, out width);
				//result.Width = width;

				//int height = 0;
				//int.TryParse(element.Attribute("Height") != null ? element.Attribute("Height").Value : null, out height);
				//result.Height = height;

				foreach (var item in element.Elements())
				{
					var sprite = SpriteItem.Create(item);
					if (sprite != null)
					{
						result.Add(sprite);
					}
				}
			}
			return result;
		}

		internal XElement ToXElement()
		{
			XElement element = new XElement("SpriteRow");
			if (this.Width > 0)
			{
				element.Add(new XAttribute("Width", this.Width));
			}
			if (this.Height > 0)
			{
				element.Add(new XAttribute("Height", this.Height));
			}
			foreach (var item in this)
			{
				element.Add(item.ToXElement());
			}
			return element;
		}
		#endregion
	}
}
